package com.ving.test.mybatis.session;


import com.ving.test.mybatis.binding.MapperMethod;
import com.ving.test.mybatis.binding.MapperRegistry;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 解析xml，有什么技术
 * <p>
 * Created by liuweijie on 2019-11-14.
 */
public class Configuration {

    private InputStream inputStream;
    private MapperRegistry mapperRegistry = new MapperRegistry();

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public MapperRegistry getMapperRegistry() {
        return mapperRegistry;
    }

    public void setMapperRegistry(MapperRegistry mapperRegistry) {
        this.mapperRegistry = mapperRegistry;
    }

    public void loadConfigurations() throws IOException{
        try{
            Document document = new SAXReader().read(inputStream);

            Element root = document.getRootElement();
            List<Element> mappers = root.element("mappers").elements("mapper");
            for (Element mapper : mappers) {
                if(mapper.attribute("resource")!=null){
                    mapperRegistry.setKnownMappers(loadXMLConfiguration(mapper.attribute("resource").getText()));
                }
                if(mapper.attribute("class")!=null){

                }
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    private Map<String, MapperMethod> loadXMLConfiguration(String resource) throws IOException {
        Map<String, MapperMethod> map = new HashMap<String, MapperMethod>();
        InputStream is = null;
        try {
            is = this.getClass().getClassLoader().getResourceAsStream(resource);
            Document document = new SAXReader().read(is);
            Element root = document.getRootElement();
            if (root.getName().equalsIgnoreCase("mapper")){
                String namespace = root.attribute("namespace").getText();
                for (Element select : (List<Element>)root.elements("select")) {
                    MapperMethod mapperMethod = new MapperMethod();
                    mapperMethod.setSql(select.getText().trim());
                    mapperMethod.setType(Class.forName(select.attribute("resultType").getText()));
                    map.put(namespace+"."+select.attribute("id").getText(),mapperMethod);

                }
            }
        } catch (ClassNotFoundException | DocumentException e) {
            e.printStackTrace();


        }finally {
            is.close();
        }
        return map;

    }
}
